<?php

namespace App\Kuafu\WaiMai\Service;

use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiCacheEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use App\Kuafu\WaiMai\Model\WaiMaiSecureCardModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class WaiMaiSecureCardService
{
    private int $shopId;

    /**
     * @param int $shopId
     */
    public function __construct(int $shopId)
    {
        $this->shopId = $shopId;
    }

    // 面向己方服务的查询安心卡
    public function getData(int $date)
    {
        // 安心卡截止至明天0点
        $ttl = strtotime(date('Ymd')) + 86400 - time();
        $card = Cache::remember(WaiMaiCacheEnum::getMtSecureCard($this->shopId), $ttl, function () use ($date) {
            return WaiMaiSecureCardModel::suffix($this->shopId)
                                        ->where('shopId', $this->shopId)
                                        ->where('date', $date)
                                        ->select('shopId', 'cardDetailList', 'tips', 'date')
                                        ->first();
        });

        if (!$card) {
            return null;
        }

        return [
            'cardDetailListFormat' => $card->cardDetailListFormat,
            'tips'                 => $card->tips,
        ];
    }

    /**
     * 从外卖接口中抓取安心卡信息
     * @param int $shopId
     * @param bool $commandRefresh
     * @return array
     * @throws WaiMaiException
     */
    public function fetchByApi(): string
    {
        $cacheKey = WaiMaiCacheEnum::getMtSecureCard($this->shopId);

        if (Cache::has($cacheKey)) {
            return 'cached';
        }

        // 饿了么没有安心卡，目前用美团的
        $card = BaseWaiMai::getIns(WaiMaiDBEnum::SOURCE_TYPE_MT_WM, $this->shopId)
                          ->getSecureCard();

        if (!$card['status']) {
            return 'statusFalse';
        }

        $syncOpenReceipt = $card['data']['syncOpenReceipt'] ?? 0;
        if (!$syncOpenReceipt) {
            return 'syncOpenReceipt 0';
        }

        $date           = date('Ymd', $card['data']['cardTime'] ?? 0);
        $cardDetailList = json_encode($card['data']['cardDetailList'] ?? '', JSON_UNESCAPED_UNICODE);
        $tips           = $card['data']['tips'] ?? '';

        DB::connection('mysqlWaiMai')->beginTransaction();

        // 先尝试删除
        WaiMaiSecureCardModel::suffix($this->shopId)->delData($this->shopId, (int)$date);

        // 插入今天的安心卡数据
        WaiMaiSecureCardModel::suffix($this->shopId)->addData($this->shopId, (int)$date, $cardDetailList, $tips);

        DB::connection('mysqlWaiMai')->commit();

        // 生成缓存
        Cache::forget(WaiMaiCacheEnum::getMtSecureCard($this->shopId));
        $this->getData($date);
        return 'success!!!';
    }
}
